from django.shortcuts import render, redirect
from web import models
from django import forms
from django.urls import reverse
from utils.BootStrapForm import BootStrapForm
from utils.link import filter_reverse


# Form 实现
class LevelForm(BootStrapForm, forms.Form):
    title = forms.CharField(
        label="标题",
        required=True,
        # widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入标题"}),
    )
    percent = forms.CharField(
        label="折扣",
        required=True,
        # widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入折扣"}),
        help_text="填入0-100整数表示百分比，例如：90，表示90%"
    )


# ModelForm 实现
class LevelModelForm(BootStrapForm, forms.ModelForm):
    class Meta:
        model = models.Level
        fields = ['title', 'percent']
        # widgets = {
        #     'title': forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入标题"}),
        #     'percent': forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入折扣"}),
        # }


def level_list(request):
    queryset = models.Level.objects.filter(active=1)
    return render(request, 'level_list.html', {'queryset': queryset})


def level_add(request):
    if request.method == "GET":
        form = LevelModelForm()
        return render(request, 'form.html', {'form': form})

    form = LevelModelForm(request.POST)
    if not form.is_valid():
        return render(request, 'form.html', {'form': form})

    form.save()

    # models.Level.objects.create(**form.cleaned_data)
    return redirect(reverse('level_list'))
    # return redirect('/level/list')


def level_edit(request, pk):
    level_object = models.Level.objects.filter(id=pk, active=1).first()
    if request.method == "GET":
        form = LevelModelForm(instance=level_object)
        return render(request, 'form.html', {'form': form})

    form = LevelModelForm(request.POST, instance=level_object)
    if not form.is_valid():
        # 只有经过 form.is_valid() 后，才可以输出 form.cleaned_data
        return render(request, 'form.html', {'form': form})
    form.save()
    return redirect(filter_reverse(request, '/level/list/'))
    # return redirect(reverse('level_list'))


def level_delete(request, pk):
    # 逻辑删除，将 active = 0
    exists = models.Customer.objects.filter(level_id=pk).exists()
    if not exists:
        models.Level.objects.filter(id=pk).update(active=0)

    return redirect(reverse('level_list'))
